package net.koodar.forge.system.support.operateLog.service;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.RequiredArgsConstructor;
import net.koodar.forge.mybatis.util.PageUtil;
import net.koodar.forge.system.support.operateLog.model.dto.OperateLogQueryDTO;
import net.koodar.forge.system.support.operateLog.model.entity.OperateLog;
import net.koodar.forge.system.support.operateLog.dao.OperateLogMapper;
import net.koodar.forge.common.domain.dto.Response;
import net.koodar.forge.common.domain.dto.SingleResponse;
import net.koodar.forge.common.exception.BizException;
import net.koodar.forge.log.event.OperateLogEvent;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @author liyc
 */
@Service
@RequiredArgsConstructor
public class OperateLogServiceImpl implements OperateLogService {

	private final OperateLogMapper operateLogMapper;

	@Override
	public Response pageBy(OperateLogQueryDTO operateLogQuery) {
		Page<OperateLog> operateLogPage = operateLogMapper.selectPage(operateLogQuery.toPage(), operateLogQuery.toQueryWrapper());
		List<OperateLog> records = operateLogPage.getRecords();
		return SingleResponse.ok(PageUtil.toPage(records, operateLogPage.getTotal()));
	}

	@Override
	public Response detail(Long operateLogId) {
		OperateLog operateLog = operateLogMapper.selectById(operateLogId);
		if (operateLog == null) {
			throw new BizException("非法参数，查询不到id:" + operateLogId);
		}
		return SingleResponse.ok(operateLog);
	}

	@Override
	public void add(OperateLogEvent event) {
		OperateLog operateLog =
				OperateLog.builder()
						.operateUserId(event.getOperateUserId())
						.operateUserName(event.getOperateUserName())
						.url(event.getUrl())
						.method(event.getMethod())
						.param(event.getParam())
						.ip(event.getIp())
						.userAgent(event.getUserAgent())
						.failReason(event.getFailReason())
						.successFlag(event.getSuccessFlag())
						.content(event.getContent())
						.module(event.getModule())
						.build();
		operateLogMapper.insert(operateLog);
	}
}
